<?php

namespace Wechat\Controller;

use Think\Controller;

class ApiController extends Controller {

    /**

     * 微信消息接口入口

     * 所有发送到微信的消息都会推送到该操作

     * 所以，微信公众平台后台填写的api地址则为该操作的访问地址

     */
    public function index($id = '') {

        import("@.Util.Wechat");

        $token = I('get.Token') ? I('get.Token') : C('token'); //微信后台填写的TOKEN



        /* 加载微信SDK */

        $wechat = new \Wechat($token);



        /* 获取请求信息 */

        $data = $wechat->request();

        $data['openid'] = $data['FromUserName'];

        if ($data && is_array($data)) {

            S('weixin', $wechat);

            S('data', $data);
        
            /**

             * 你可以在这里分析数据，决定要返回给用户什么样的信息

             * 接受到的信息类型有9种，分别使用下面九个常量标识

             * Wechat::MSG_TYPE_TEXT       //文本消息

             * Wechat::MSG_TYPE_IMAGE      //图片消息

             * Wechat::MSG_TYPE_VOICE      //音频消息

             * Wechat::MSG_TYPE_VIDEO      //视频消息

             * Wechat::MSG_TYPE_MUSIC      //音乐消息

             * Wechat::MSG_TYPE_NEWS       //图文消息（推送过来的应该不存在这种类型，但是可以给用户回复该类型消息）

             * Wechat::MSG_TYPE_LOCATION   //位置消息

             * Wechat::MSG_TYPE_LINK       //连接消息

             * Wechat::MSG_TYPE_EVENT      //事件消息

             *

             * 事件消息又分为下面五种

             * Wechat::MSG_EVENT_SUBSCRIBE          //订阅

             * Wechat::MSG_EVENT_SCAN               //二维码扫描

             * Wechat::MSG_EVENT_LOCATION           //报告位置

             * Wechat::MSG_EVENT_CLICK              //菜单点击

             * Wechat::MSG_EVENT_MASSSENDJOBFINISH  //群发消息成功

             */
            //根据来源信息的类型使用不同的方法路径进行处理

            Switch ($data['MsgType']) {

                case \Wechat::MSG_TYPE_TEXT: //文本

                    $arr = $this->text($data);

                    break;



                case \Wechat::MSG_TYPE_IMAGE: //图片

                    $arr = image($data);

                    break;



                case \Wechat::MSG_TYPE_EVENT: //事件

                    $arr = $this->event($data);
                    
                    break;



                default:

                    $content = "该功能暂未开放"; //回复内容，回复不同类型消息，内容的格式有所不同

                    $type = 'text'; //回复消息的类型
            }

            /////////////////////////////////////////////////////////////////////

            $content = $arr['content'] ? $arr['content'] : $content;

            $type = $arr['type'] ? $arr['type'] : $type;

            /* 响应当前请求(自动回复) */

            S('content', $content);

            if(empty($arr) || !isset($arr) || $arr == null) {
                exit("");
            } 

            $wechat->response($content, $type);
            /**

             * 响应当前请求还有以下方法可以只使用

             * 具体参数格式说明请参考文档

             * 

             * $wechat->replyText($text); //回复文本消息

             * $wechat->replyImage($media_id); //回复图片消息

             * $wechat->replyVoice($media_id); //回复音频消息

             * $wechat->replyVideo($media_id, $title, $discription); //回复视频消息

             * $wechat->replyMusic($title, $discription, $musicurl, $hqmusicurl, $thumb_media_id); //回复音乐消息

             * $wechat->replyNews($news, $news1, $news2, $news3); //回复多条图文消息

             * $wechat->replyNewsOnce($title, $discription, $url, $picurl); //回复单条图文消息

             * 

             */
        }
    }

    /////////////////////////////////
    //分支功能

    protected function text($data) {

        switch ($data['Content']) {

            /* case "骑游深圳红树林":

              $arr['content'] = "恭喜您获得由【ofo骑游】提供的10元租车优惠券一张，您可凭此信息在快车道自行车行享受优惠租车一次，祝您骑行愉快！"; //回复内容，回复不同类型消息，内容的格式有所不同

              $arr['type']    = 'text'; //回复消息的类型

              break; */
            /*
              case "支付":
              echo $this->send_Pic_Text_forBusinessPay($data);
              $arr = null;

              exit();
              break;
              case "申请OFO骑游店主":

              $ArticleCount = 1;
              $newsTpl = "<xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[%s]]></MsgType>
              <ArticleCount>%s</ArticleCount>
              <Articles>
              <item>
              <Title><![CDATA[%s]]></Title>
              <Description><![CDATA[%s]]></Description>
              <PicUrl><![CDATA[%s]]></PicUrl>
              <Url><![CDATA[%s]]></Url>
              </item>
              </Articles>
              </xml>";

              $resultStr = sprintf($newsTpl, $data['FromUserName'], $data['ToUserName'], time(), 'news',
              $ArticleCount,'申请店主','申请店主请点击页面填写信息','http://www.ofo.so/Template/images/pic01.jpg',
              'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.C('appid').'&redirect_uri=http://'.$_SERVER['SERVER_NAME'].'/Wechat/Api/auth/&response_type=code&scope=snsapi_base&state=business&connect_redirect=1#wechat_redirect');
              echo $resultStr;

              $arr = null;

              exit();
              break; */

            default:
                /* if($sql = M('response')->where("`from` like '%$data[Content]%'") -> find()){

                  $arr['content'] = $sql['to'];

                  $arr['type']    = 'text'; //回复消息的类型

                  //添加回复统计

                  $user = M('User')->where("openid = '".$data["openid"]."'")->find();

                  $responseDetail = M('ResponseDetail')->where("responseid = ".$sql['id']." and openid = '".$user['openid']."'")->find();

                  if(!$responseDetail) {
                  $responseDetail = M('ResponseDetail');
                  $rdata['time'] = time();
                  $rdata['openid'] = $data['openid'];
                  $rdata['responseid'] = $sql['id'];
                  $rdata['uid'] = $user['uid'];
                  $responseDetail->create();
                  $responseDetail->add($rdata);
                  }

                  }else{ */



                //$arr['content'] = '欢迎来到ofo'; //回复内容，回复不同类型消息，内容的格式有所不同
                //$arr['type'] = 'text'; //回复消息的类型
                $arr = null;
                /* 	} */

                break;
        }



        return $arr;
    }

    protected function event($data) {

        switch ($data['Event']) {

            case \Wechat::MSG_EVENT_SUBSCRIBE:  //关注

                $arr['content'] = "尊敬的用户：欢迎您使用优友陪玩系统，本系统只有用户取得胜利，陪玩的打手才能得到钱，您不赢，我们打手不收钱。

在您填写游戏昵称时，请一定要填写正确，建议您使用复制粘贴保证是准备的游戏昵称，如果昵称错误，您将无法使用本系统。

想成为打手的朋友们请在“我的”中选择申请打手，我们会严格审查您的陪打能力，如果通过会有丰厚佣金等您来赚。

当您成为打手后，用电脑端登录“http://skyyoyo.com/Home”页面，视为激活打手状态，可以接单。在您不准备陪打接单的时候请您及时关闭网页。";

                $arr['type'] = 'text'; //回复消息的类型

                break;

            case unsubscribe:  //取消关注

//                cookie('openid', null);
//                
//                $userdata['subscribe'] = '0';
//
//                M('User')->where("openid = '" . $data["openid"] . "'")->save($userdata);
                
                break;

            default:

                $arr['content'] = $data['Event']."事件暂未开放"; //回复内容，回复不同类型消息，内容的格式有所不同
                $arr['type']    = 'text'; //回复消息的类型

                break;
        }

        return $arr;
    }

    protected function click($data) {

        switch ($data['EventKey']) {



            case baodian:

                $arr['content'] = array(
                    array(
                        "一分钟，你能不能更持久 | ofo一分钟公益骑行",
                        "ofo一分钟公益骑行火热进行中",
                        'http://mp.weixin.qq.com/s?__biz=MzAxNzAzMTExOA==&mid=204044895&idx=1&sn=3b34c6f64bb9afc6d23d0c3c039de67e#rd',
                        'https://mmbiz.qlogo.cn/mmbiz/zLvQJdMzyqFGkLmewmHgyaxj3jUwNWGGK8vLIweWq5gZRPET2MFcQRKJWsiaCzMJ8ibmD4JygqgtrbmoT06npSag/0'
                    )
                );

                $arr['type'] = 'news'; //回复消息的类型

                break;



            case taiwan:

                $arr['content'] = array(
                    array(
                        "报名 | 台湾岛西线11天骑游吃喝之旅",
                        "唯有美食与美景不可辜负！这个假期，吃吃吃吃吃~吃遍台湾西部各大夜市！",
                        'http://mp.weixin.qq.com/s?__biz=MzAxNzAzMTExOA==&mid=204110685&idx=1&sn=794dbc7a3e14b86045ad7dfce565a22a#rd',
                        'https://mmbiz.qlogo.cn/mmbiz/zLvQJdMzyqEwgt7icNxGTgULLFUHQACBZxN3iacMGiakVf4LpQx7TkWUnrwiavtwticuSiaIGibQiacqbLscPsCwUeDNxQ/0'
                    )
                );

                $arr['type'] = 'news'; //回复消息的类型

                break;



            case hainan:

                $arr['content'] = array(
                    array(
                        "报名 | 海南岛东线6天骑游探索之旅",
                        "厌倦了跟着旅行团匆忙参观？受够了每回必备的漫长购物？隔海相望的海南，奇景、美食，等待你深度接触！",
                        'http://mp.weixin.qq.com/s?__biz=MzAxNzAzMTExOA==&mid=204105985&idx=1&sn=6926bd819a97454ba9ffc09b6db9e8c6#rd',
                        'https://mmbiz.qlogo.cn/mmbiz/zLvQJdMzyqEDC8ORBFx01HNRFqayWZzbqd3YHd6libAcWL4icdZ00OIfug0MCI1NyUdgDPJ01rQbZEUoskjt6oOA/0'
                    )
                );

                $arr['type'] = 'news'; //回复消息的类型

                break;



            case about:

                $arr['content'] = "ofo骑游，中国骑行旅游第一品牌！ 踏上单车，跟着我们一起去探索世界！ 更多精彩旅行，欢迎全天候随时骚扰4006-927-929 另有新浪官方微博@ofo骑游 ，积极调戏主页菌会有惊喜哟";

                $arr['type'] = 'text'; //回复消息的类型

                break;



            case free:

                $db = M('user');

                $sql = $db->where("openid = '$data[openid]'")->find();

                S('sql', $sql);

                $url = "http://" . $_SERVER['HTTP_HOST'] . U('Wechat/item/add?uid=' . $sql[uid]);

                $arr['content'] = "地址" . $url;

                $arr['content'] = "用户$sql[uid]:<a href=\"$url\">点击发布活动</a>";



                $arr['type'] = 'text'; //回复消息的类型

                break;



            case look:

                $db = M('user');

                $sql = $db->where("openid = '$data[openid]'")->find();

                $url = "http://" . $_SERVER['HTTP_HOST'] . U('Wechat/index/index?uid=' . $sql[uid]);

                $arr['content'] = "地址" . $url;



                $arr['content'] = "用户$sql[uid]:<a href=\"$url\">点击浏览活动</a>";





                $arr['type'] = 'text'; //回复消息的类型

                break;



            default:

                $arr['content'] = "该功能暂未开放"; //回复内容，回复不同类型消息，内容的格式有所不同

                $arr['type'] = 'text'; //回复消息的类型

                break;
        }



        return $arr;
    }

    protected function image($data) {

        $arr['content'] = "你是说：" . $data['Content']; //回复内容，回复不同类型消息，内容的格式有所不同

        $arr['type'] = 'text'; //回复消息的类型

        return $arr;
    }

    /////////////////////////////
    //自定义菜单功能



    function menulist() {

        echo $url = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token=' . access_token();

        //$post = array(124,535,635,42);

        $arr = json_decode(curl($url), true);

        dump($arr);

        echo "<br/>";

        dump(json_encode($arr));
    }

    function menuadd() {

        if (I('get.key') != 'luoe123') {

            exit("参数错误");
        }

        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . access_token();

        $data = resetMenu();

        //dump($post);

        dump($data);

        $aaa = curl($url, $data);

        dump($aaa);
    }

    //////////////////////////////////
    /// view获取openid



    function auth() {

        //dump(I('get.'));

        $state = I('get.state');

        $pstr = I('get.pstr');
        $code = I('get.code');

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('appid') . "&secret=" . C('appsecret') . "&code=" . $code . "&grant_type=authorization_code";

        $r = json_decode(curl($url), true);

        //dump($r);

        $openid = $r['openid'];

        $db = M('user');

        $sql = $db->where("openid = '$openid'")->find();

        cookie('uid', $sql['uid'], 0);
        
        cookie('openid', $sql['openid'], 0);
 
    }

    function auth2() {

        $code = '04143f67c046f5e587ae729d6cbef9fH';

        echo $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('appid') . "&secret=" . C('appsecret') . "&code=" . $code . "&grant_type=authorization_code";

        $r = json_decode(curl($url), true);

        dump($r);
    }

    function auth3() {

        $state = I('get.state');

        $code = I('get.code');

        $t = explode(',', $state);

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('appid') . "&secret=" . C('appsecret') . "&code=" . $code . "&grant_type=authorization_code";

        $r = json_decode(curl($url), true);

        $openid = $r['openid'];
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $r['access_token'] . "&openid=" . $openid . "&lang=zh_CN";

        $r = json_decode(curl($url), true);

        $userMap['token'] = $t[1];

        $user = D('user')->where($userMap)->find();
        $user['openid'] = $openid;

        if(isNullOrEmpty($user['user_name'])) {
            $user['user_name'] = $r['nickname'];
        }

        if(isNullOrEmpty($user['head_image_url'])) {
            $user['head_image_url'] = $r['headimgurl'];
        }

        D('user')->where($userMap)->save($user);

        header("Location: " . urldecode($t[0]));

    }

    ///////////////////////////
    //客服消息

    function send($openid, $text) {

        //$uid = I('get.openid');
        //$text = I('post.text');
        //$uid = 'ozj3Us5MtH-WdZJ8cvZWfYMuj4CQ';

        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . access_token();

        $post = array(
            "touser" => $openid,
            "msgtype" => "text",
            "text" => array(
                "content" => $text,
            ),
        );

        $data = json_encode2($post);

        $aaa = curl($url, $data);

        return $aaa;
    }

    /////////////////////////
    //用户功能

    function userlist() {

        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . access_token();
        if (I('get.openid')) {
            $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . access_token() . "&next_openid=" . I('get.openid');
        }
        $arr = curl($url);

        $arr2 = json_decode($arr, true);

        S('Wechat_user_list', $arr2[data][openid]);

        dump($arr2[data][openid]);
    }

    function userxiufu() {

        G('begin');
        //$this -> userlist();

        $user_list = S('Wechat_user_list');

        $user = D('User');



        $yes = 0;

        $no = 0;

        foreach ($user_list as $val) {

            $data['openid'] = $val;



            /* if(!$user->create($data)){

              echo $user->getError()."||".$data['openid']."<br />";

              }else{

              echo "可以写入".$data['openid']."<br />";

              $user -> add($data);

              }

             */

            //$user -> create($data);

            if ($user->where($data)->find()) {

                echo "<br />重复了" . $val;

                $yes++;
            } else {

                echo "<br />准备写入" . $val;

                $uid = $user->add($data);

                $update = A('User');

                $update->updata($uid);

                $no++;
            }

            //$user -> add($data);
        }

        echo "<br/>当前写入" . $no . "已存在" . $yes;

        G('end');

        echo "<br/>执行时间：" . G('begin', 'end') . 's';
    }

    /////////////////////////////////////////
    //短信

    protected function sms($tel, $content) {

        $ch = curl_init();



        curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/status.json");

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        curl_setopt($ch, CURLOPT_HEADER, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);



        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

        curl_setopt($ch, CURLOPT_USERPWD, 'api:key-' . C('mmskey'));



        $res = curl_exec($ch);

        curl_close($ch);

        //$res  = curl_error( $ch );

        dump($res);
    }

    //////////////////////////////////
    //调试

    function debug() {

        dump(S('weixin'));

        dump(S('data'));

        dump(S('SUBSCRIBE'));

        dump(S('sql'));

        dump(S('code'));

        //dump(S('Wechat_user_list'));
    }

    function debug2() {





        dump($sql1);
    }

    protected function send_Pic_Text_forBusinessPay($data) {
        $businessName = $data['Content'];
        $where['from'] = $businessName;
        $response = D('Response');
        $responseid = $response->where($where)->find();

        if ($responseid) {
            //$fp = fopen('1api.txt','a+');
            //fwrite($fp,$responseid['id']);
            //fclose($fp);
        }


        $ArticleCount = 1;
        $newsTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<ArticleCount>%s</ArticleCount>
						<Articles>
							<item>
								<Title><![CDATA[%s]]></Title>
								<Description><![CDATA[%s]]></Description>
								<PicUrl><![CDATA[%s]]></PicUrl>
								<Url><![CDATA[%s]]></Url>
							</item>
						</Articles>
					</xml>";

        $resultStr = sprintf($newsTpl, $data['FromUserName'], $data['ToUserName'], time(), 'news', $ArticleCount, '支付', '向' . $data['Content'] . '店主支付', 'http://www.ofo.so/Template/images/pic01.jpg', 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . C('appid') . '&redirect_uri=http://' . $_SERVER['SERVER_NAME'] . '/Wechat/Api/auth/&response_type=code&scope=snsapi_base&state=businesspay_' . $responseid['id'] . '&connect_redirect=1#wechat_redirect');
        return $resultStr;
    }

    public function WechatPay(){
    
        $order=$GLOBALS["HTTP_RAW_POST_DATA"];

        $array_data = json_decode(json_encode(simplexml_load_string($order, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if($array_data['return_code']=='SUCCESS') {

            echo 'SUCCESS';

            //查找付款记录
            $payMap['out_trade_no'] = $array_data['out_trade_no'];
            $pay = M('pay')->where($payMap)->find();

            //修改付款状态
            $payData['status'] = 1;

            M('pay')->where($payMap)->save($payData);

            //修改订单状态
            $orderMap['pay_id'] = $pay['pay_id'];
            $order = M('order')->alias('o')
                ->join('left join __USER__ u ON o.user_id = u.user_id')
                ->join('left join __ORDER_ITEM__ oi ON o.order_id = oi.order_id')
                ->join('left join __LADDER__ l ON oi.ladder_id = l.ladder_id')
                ->join('left join __USER__ uu on l.user_id = uu.user_id')
                ->field('o.*, u.mobile as player_mobile, uu.mobile as ladder_mobile')
                ->where($orderMap)
                ->find();

            $orderData['status'] = 1;

            M('order')->where($orderMap)->save($orderData);

            //修改订单项目状态
            $orderItemMap['order_id'] = $order['order_id'];

            $orderItemData['status'] = 1;
            $orderItemData['begin_time'] = getCurrentDate();

            M('orderItem')->where($orderItemMap)->save($orderItemData);

            //发送短信提示匹配成功
            $content = "您的订单已匹配成功，请查看公众账号内订单信息，进入游戏，互加好友，祝游戏顺利！";

            //发送给用户
            mms(C('mmskey'), $order['player_mobile'], $content);
            //发送给打手
            mms(C('mmskey'), $order['ladder_mobile'], $content);

        }
    }
    /**
     * 订单支付成功
     * @param type $money
     * @param type $param
     */
    public function pay($money, $param) {
    	
        $orderId = $param['orderId'];
        
        $order = M('order')->where('order_id='.$orderId)->find();
        
        $pay = M('pay')->where('pay_id='.$order['pay_id'])->find();
        
    	$payMap['pay_id'] = $pay['pay_id'];       
        $payData['status'] = 1;
        $payData['update_time'] = time();
        $payData['pay_source'] = 0;
        $payData['callback'] = 'http://wx.congyicn.com/Wechat/Api/Pay/orderId='.$orderId;
        
        M('pay')->where($payMap)->save($payData);

        $orderMap['order_id'] = $orderId;

        $orderData['status'] = 1;
        $orderData['pay_time'] = time();

        M('order')->where($orderMap)->save($orderData);

    }

}
